<template>
    <el-row class="sms-code">
        <el-col :span="24">
            <el-input v-model="smsCode" placeholder="验证码" maxlength="6"></el-input>
        </el-col>
        <el-col :span="24" class="btn">
            <span class="line">|</span>
            <div class="time" @click="sendHandler">
                <span :class="[disabled ? 'time-text' : 'btn-text']">{{ btnText }}</span>
            </div>
        </el-col>
    </el-row>
</template>
<script setup>
import { computed, ref, inject } from 'vue';
import request from '@/request';
import { isNotEmpty } from '../commons/utils';
const bus = inject('bus');

const props = defineProps({
    mobile: String,
    from: String,
    modelValue: String
});
const emit = defineEmits(['update:modelValue']);
const smsCode = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

let btnText = ref('获取验证码');
const initSecond = 60;
let currentSecond = ref(initSecond);
let intervalId = null;
const from = computed(() => props.from);
const mobile = computed(() => props.mobile);
const disabled = computed(() => btnText.value !== '获取验证码');

/**
 * 设置按钮文本
 */
const setNewText = () => {
    btnText.value = `重新发送(${currentSecond.value}秒)`;
    currentSecond.value--;
    if (currentSecond.value === -1) {
        btnText.value = `获取验证码`;
        clearInterval(intervalId);
        currentSecond.value = initSecond;
    }
};

/**
 * 创建倒计时
 */
const createInterval = () => {
    intervalId = setInterval(setNewText, 1000);
};

/**
 * 执行倒计时
 */
const countdownHandler = () => {
    setNewText();
    createInterval();
};

/**
 * 发送短信
 */
const sendHandler = async () => {
    if (!disabled.value) {
        if (isNotEmpty(mobile.value)) {
            await request('sendSmsCodeServ', { mobile: mobile.value, from: from.value });
            countdownHandler();
        } else {
            bus.emit('sendSms:noMobile');
        }
    }
};
</script>
<style lang="scss" scoped>
.sms-code {
    position: relative;
    width: 100vw;
    .btn {
        position: absolute;
        right: 12px;
        display: flex;
        flex-direction: row;

        .line {
            margin-right: 10px;
            color: #969696;
        }

        .time {
            max-width: 100px;
            text-align: right;

            .btn-text {
                color: #33302d;
                cursor: pointer;
            }

            .time-text {
                color: #969696;
            }
        }
    }
}
</style>
